package com.lyfei.yd.upload;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.google.gson.Gson;
import com.lyfei.yd.common.utils.uuid.UUID;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Component
public class OssUtils {
    private static String endPoint = "oss-cn-hangzhou.aliyuncs.com";

    private static String accessKeyId = "LTAI5tSh718fa5CPJP8NSn6b";

    private static String accessKeySecret = "fIpnmcMf0WmD4WuKNBU7xkJqPAW9ka";

    private static String bucketName = "curtain";

    private static String path = "https://img.xiaoyi666.cn/";

    private static final OSS ossClient;


    static {
        ossClient = new OSSClientBuilder().build(endPoint, accessKeyId, accessKeySecret);
    }

    public static List<String> upload(MultipartFile file) {
        List<String> result=new ArrayList<>();
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String fileName = getRandomImgName(Objects.requireNonNull(file.getOriginalFilename()));
        result.add(fileName);
        ossClient.putObject(bucketName, fileName, inputStream);
        result.add(path + fileName);
        return result;
    }

    public static String getRandomImgName(String fileName) {
        int index = fileName.lastIndexOf(".");

        if (fileName.isEmpty() || index == -1){
            throw new IllegalArgumentException();
        }
        // 获取文件后缀
        String suffix = fileName.substring(index).toLowerCase();
        // 生成UUID
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        // 拼接新的名称
        return uuid + suffix;
    }

}
